<?php
namespace app\rbac\controller;
use app\rbac\model\AdminM;
use think\Db;
use think\Session;
use app\base\controller\Base;

class Admin extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 新增
     * @return mixed
     */
    public function add()
    {
        if($this->request->isPost())
        {
            $data = $this->request->post();
            $model = new AdminM();
            $model->add($data);
            return json(['code'=>$model->code,'msg'=>$model->msg]);
        }
        $roleData = DB::table('role')->where('is_usable',1)->field('id,role_name')->select();
        $this->assign(array(
            '_page_title'=>'添加管理员',
            '_page_title_english'=>'Administrators add',
            '_btn_title'=>'管理员列表',
            '_btn_link'=>'lst',
            '_page_ico'=>'iconfa-user',
            'roleData'=>$roleData,
        ));
        return $this->fetch();
    }



    /**
     * 编辑页面
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        if($this->request->isPost())
        {
            $data = $this->request->post();
            $model = new AdminM();
            $model->edit($data);
            return json(['code'=>$model->code,'msg'=>$model->msg]);
        }
        $data = Db::table('admin')
            ->alias('a')
            ->join('admin_role ar','ar.admin_id = a.id','LEFT')
            ->where(['a.id'=>$id])
            ->field('a.id,a.admin_name,a.email,GROUP_CONCAT(ar.role_id) as role_ids')
            ->group('a.id')
            ->find();
        $data['role_ids'] = explode(',',$data['role_ids']);
        $roleData = DB::table('role')->where('is_usable',1)->field('id,role_name')->select();
        $this->assign(array(
            '_page_title'=>'编辑管理员',
            '_page_title_english'=>'Administrators edit',
            '_btn_title'=>'管理员列表',
            '_btn_link'=>url('lst'),
            '_page_ico'=>' iconfa-user',
            'data'=>$data,
            'roleData'=>$roleData,
        ));
        return $this->fetch();
    }

    /**
     * 获取全部数据
     * @return mixed
     */
    public function lst()
    {
        $model = new AdminM();
        $data = $model->lst();
        $page = $data->render();
        $this->assign(array(
            '_page_title'=>'管理员列表',
            '_page_title_english'=>'Administrators list',
            '_btn_title'=>'添加管理员',
            '_btn_link'=>url('add'),
            '_page_ico'=>' iconfa-user',
            'data'=>$data,
            'page'=>$page,
        ));
        return $this->fetch();
    }


    /**
     * 删除数据
     * @param $id
     */
    public function del()
    {
        $id = $this->request->post('id');
        $model = new AdminM();
        $model->del($id);
        return json(['code'=>$model->code,'msg'=>$model->msg]);
    }


}
